import * as THREE from 'three';

export class PerformanceOptimizer {
    constructor(app) {
        this.app = app;
        this.frameCount = 0;
        this.lastFrameTime = performance.now();
        this.averageFPS = 60;
        this.targetFPS = 60;
        this.adaptiveQuality = true;
        
        // 性能监控
        this.performanceMetrics = {
            fps: 60,
            drawCalls: 0,
            triangles: 0,
            geometries: 0,
            textures: 0,
            programs: 0
        };
        
        // 质量等级
        this.qualityLevels = {
            LOW: {
                pixelRatio: 1,
                shadowMapSize: 512,
                antialias: false,
                maxLights: 2,
                particleCount: 0.3
            },
            MEDIUM: {
                pixelRatio: Math.min(window.devicePixelRatio, 1.5),
                shadowMapSize: 1024,
                antialias: true,
                maxLights: 4,
                particleCount: 0.6
            },
            HIGH: {
                pixelRatio: Math.min(window.devicePixelRatio, 2),
                shadowMapSize: 2048,
                antialias: true,
                maxLights: 8,
                particleCount: 1.0
            }
        };
        
        this.currentQuality = 'HIGH';
        this.autoAdjustmentEnabled = true;
        
        this.init();
    }
    
    init() {
        // 检测设备性能
        this.detectDeviceCapabilities();
        
        // 应用初始质量设置
        this.applyQualitySettings(this.currentQuality);
        
        console.log(`性能优化器初始化完成，当前质量: ${this.currentQuality}`);
    }
    
    detectDeviceCapabilities() {
        const canvas = document.createElement('canvas');
        const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
        
        if (!gl) {
            this.currentQuality = 'LOW';
            return;
        }
        
        // 检测GPU信息
        const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
        let gpu = 'Unknown';
        if (debugInfo) {
            gpu = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
        }
        
        // 检测设备内存
        const memory = navigator.deviceMemory || 4;
        
        // 检测硬件并发数
        const cores = navigator.hardwareConcurrency || 4;
        
        // 基于检测结果调整质量
        if (memory < 4 || cores < 4 || gpu.includes('Intel')) {
            this.currentQuality = 'LOW';
        } else if (memory < 8 || cores < 8) {
            this.currentQuality = 'MEDIUM';
        } else {
            this.currentQuality = 'HIGH';
        }
        
        console.log(`设备检测结果: GPU=${gpu}, 内存=${memory}GB, 核心=${cores}, 质量=${this.currentQuality}`);
    }
    
    applyQualitySettings(quality) {
        const settings = this.qualityLevels[quality];
        if (!settings) return;
        
        const renderer = this.app.getRenderer();
        
        // 调整像素比
        renderer.setPixelRatio(settings.pixelRatio);
        
        // 调整阴影质量
        if (renderer.shadowMap && renderer.shadowMap.enabled && settings.shadowMapSize) {
            try {
                renderer.shadowMap.mapSize.setScalar(settings.shadowMapSize);
            } catch (error) {
                console.warn('无法设置阴影贴图大小:', error);
            }
        }
        
        // 通知场景调整质量
        if (this.app.sceneManager) {
            this.app.sceneManager.getAllScenes().forEach(scene => {
                if (scene.adjustQuality) {
                    scene.adjustQuality(settings);
                }
            });
        }
        
        this.currentQuality = quality;
    }
    
    update() {
        this.frameCount++;
        const currentTime = performance.now();
        const deltaTime = currentTime - this.lastFrameTime;
        
        // 每秒更新一次性能指标
        if (deltaTime >= 1000) {
            this.updatePerformanceMetrics();
            
            // 自动调整质量
            if (this.autoAdjustmentEnabled) {
                this.autoAdjustQuality();
            }
            
            this.frameCount = 0;
            this.lastFrameTime = currentTime;
        }
        
        // 执行每帧优化
        this.performFrameOptimizations();
    }
    
    updatePerformanceMetrics() {
        const renderer = this.app.getRenderer();
        
        // 计算FPS
        this.performanceMetrics.fps = this.frameCount;
        this.averageFPS = this.averageFPS * 0.9 + this.performanceMetrics.fps * 0.1;
        
        // 获取渲染统计
        if (renderer.info) {
            this.performanceMetrics.drawCalls = renderer.info.render.calls;
            this.performanceMetrics.triangles = renderer.info.render.triangles;
            this.performanceMetrics.geometries = renderer.info.memory.geometries;
            this.performanceMetrics.textures = renderer.info.memory.textures;
            this.performanceMetrics.programs = renderer.info.programs?.length || 0;
        }
    }
    
    autoAdjustQuality() {
        const targetFPS = this.targetFPS;
        const currentFPS = this.averageFPS;
        
        if (currentFPS < targetFPS * 0.8) {
            // FPS过低，降低质量
            if (this.currentQuality === 'HIGH') {
                this.applyQualitySettings('MEDIUM');
                console.log('性能不足，降低到中等质量');
            } else if (this.currentQuality === 'MEDIUM') {
                this.applyQualitySettings('LOW');
                console.log('性能不足，降低到低质量');
            }
        } else if (currentFPS > targetFPS * 1.2) {
            // FPS过高，可以提升质量
            if (this.currentQuality === 'LOW') {
                this.applyQualitySettings('MEDIUM');
                console.log('性能充足，提升到中等质量');
            } else if (this.currentQuality === 'MEDIUM') {
                this.applyQualitySettings('HIGH');
                console.log('性能充足，提升到高质量');
            }
        }
    }
    
    performFrameOptimizations() {
        // 视锥剔除优化
        this.performFrustumCulling();
        
        // 距离剔除优化
        this.performDistanceCulling();
        
        // LOD优化
        this.performLODOptimization();
    }
    
    performFrustumCulling() {
        const camera = this.app.getCamera();
        const frustum = new THREE.Frustum();
        const matrix = new THREE.Matrix4().multiplyMatrices(
            camera.projectionMatrix, 
            camera.matrixWorldInverse
        );
        frustum.setFromProjectionMatrix(matrix);
        
        // 对所有场景对象执行视锥剔除
        if (this.app.sceneManager) {
            const currentScene = this.app.sceneManager.getCurrentScene();
            if (currentScene && currentScene.performFrustumCulling) {
                currentScene.performFrustumCulling(frustum);
            }
        }
    }
    
    performDistanceCulling() {
        const camera = this.app.getCamera();
        const maxDistance = 100; // 最大渲染距离
        
        if (this.app.sceneManager) {
            const currentScene = this.app.sceneManager.getCurrentScene();
            if (currentScene && currentScene.performDistanceCulling) {
                currentScene.performDistanceCulling(camera.position, maxDistance);
            }
        }
    }
    
    performLODOptimization() {
        const camera = this.app.getCamera();
        
        if (this.app.sceneManager) {
            const currentScene = this.app.sceneManager.getCurrentScene();
            if (currentScene && currentScene.performLODOptimization) {
                currentScene.performLODOptimization(camera.position);
            }
        }
    }
    
    setQuality(quality) {
        if (this.qualityLevels[quality]) {
            this.applyQualitySettings(quality);
            console.log(`手动设置质量为: ${quality}`);
        }
    }
    
    setAutoAdjustment(enabled) {
        this.autoAdjustmentEnabled = enabled;
        console.log(`自动质量调整: ${enabled ? '启用' : '禁用'}`);
    }
    
    getPerformanceMetrics() {
        return { ...this.performanceMetrics };
    }
    
    getCurrentQuality() {
        return this.currentQuality;
    }
    
    getAverageFPS() {
        return Math.round(this.averageFPS);
    }
}
